package com.ydlclass.serialize.impl;

import com.ydlclass.Transport.message.Request.RequestPayload;
import com.ydlclass.exceptions.SerializeException;
import com.ydlclass.serialize.AbstractSerialize;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * JDK序列化
 * @Author duWenJian
 * @Date 2024/2/22 20:48
 * @Version 1.0
 */
@Slf4j
public class JdkSerialize extends AbstractSerialize implements Serializable {
    @Override
    public byte[] serialize(Object obj) {
        if (obj == null){
            return null;
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos);)
        {
            oos.writeObject(obj);
            if (log.isDebugEnabled()) {
                log.debug("对象:{}完成了序列化序列化后的body为:{}",obj.getClass(),baos.toString());
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("序列化发生异常:{}",e);
            throw new SerializeException("对body进行序列化发生错误");
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<?> clazz) {
        if (bytes == null || clazz == null){
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois  = new ObjectInputStream(bais);) {
             Object object = ois.readObject();
            if (log.isDebugEnabled()) {
                log.debug("对象:{}完成了反序列化序列化后的body为:{}",clazz,object);
            }
             return (T)object;
        } catch (IOException | ClassNotFoundException e) {
            log.error("请求反序列化发生异常:{}",e);
            throw new SerializeException("对body进行反序列化发生错误");
        }
    }
}
